package com.adu.music.spider;

import com.adu.music.api.MusicApi;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author duchuanchuan
 * @date 2017/1/1
 */
public class SongPLSpider extends AbstractSpider {

    private int pageIndex = 0;
    private final int pageSize = 100;

    @Override
    protected void initTaskQueue() {
        List<Map<String, Object>> playlists = queryPlaylistsByIndex(pageIndex);
        playlists.forEach(pl -> putTaskToQueue(pl.get("id")));
        pageIndex++;
    }

    private List<Map<String, Object>> queryPlaylistsByIndex(int index) {
        String sql = "select id from playlist limit :offset,:size";
        Map<String, Object> paramMap = new HashMap<>(2);
        paramMap.put("offset", pageSize * index);
        paramMap.put("size", pageSize);
        return asyncNamedParameterJdbcTemplate.queryForList(sql, paramMap);
    }

    @Override
    protected void produceTask() {
        while (true) {
            List<Map<String, Object>> playlists = queryPlaylistsByIndex(pageIndex);
            playlists.forEach(pl -> putTaskToQueue(pl.get("id")));
            if (playlists.size() < pageSize) break;
            pageIndex++;
        }
    }

    @Override
    protected void consumeTask(Object task) {
        String playlistId = String.valueOf(task);
        final String sql = "insert into song(id,name,artist_id,artist_name,album_id,album_name,comment) " +
                "values(:id,:name,:artist_id,:artist_name,:album_id,:album_name,:comment) " +
                "ON DUPLICATE KEY UPDATE comment=values(comment),updated_at=now()";
        List<Map<String, Object>> songs = MusicApi.crawlSongList(playlistId);
        songs.forEach(song -> asyncNamedParameterJdbcTemplate.update(sql, song));
    }
}
